angular.module('BarcodeReplace')

.controller('BarcodeReplace.HomeCtrl', ['$scope', '$state', 'BarcodeReplaceHomeService', 'User','Device', 'imanDialog', '$ionicLoading', 'imanUsbPort', '$ionicModal', function($scope, $state, BarcodeReplaceHomeService, User,Device, imanDialog, $ionicLoading, imanUsbPort, $ionicModal) {
   
     $scope.data = {
        //当前显示的单品信息
        one:{},
        //新扫描的条码
        newBarcode:"",
        //初始的条码 = 搜索的条码
        initBarcode:""

     };
     var initBarcodeMaster = 0;
     imanDialog.alert("请先手工输入原芯片ID");

     $scope.search = function(search){
        $scope.data.initBarcode = search;
        imanDialog.showLoading();
        BarcodeReplaceHomeService.getBarcodeData(search).then(function(barcodedata) {
            
            initBarcodeMaster = barcodedata._id;
            if (barcodedata != null) {
                //芯片失效，取此芯片主档装配关系中最新的条码主档信息
                if(barcodedata.Status===5){
                   BarcodeReplaceHomeService.getNewBarcodeData(initBarcodeMaster).then(function(data){
                      if(data != null){
                        imanDialog.hideLoading();
                        imanDialog.alert("芯片失效，取得此芯片最新绑定的条码信息", "");
                        $scope.data.one = data;
                      }
                      else{
                        imanDialog.hideLoading();
                        imanDialog.alert("单品数据为空", "");
                      }
                         
                   },function(error){
                      imanDialog.hideLoading();
                   });
                }
                //未失效，取当前的主档信息
                else{
                  imanDialog.hideLoading();
                  $scope.data.one = barcodedata;
                }

            } else {
                imanDialog.hideLoading();
                imanDialog.alert("单品数据为空", "");
            }
            
        }, function(error) {
            imanDialog.hideLoading();
        });

     }; 

     $scope.submitData  = function(){
        imanDialog.showLoading();
        BarcodeReplaceHomeService.submitBarcodeData($scope.data.one,$scope.data.newBarcode,initBarcodeMaster).then(function(data) {
            imanDialog.hideLoading();
            if (data != null) {
                if(data){
                    imanDialog.alert("新芯片绑定成功", "");
                }
                else{
                    imanDialog.alert("新芯片绑定失败", "");
                }

            } else {
                imanDialog.alert("单品数据为空", "");
            }
            
        }, function(error) {
            imanDialog.hideLoading();
        });
     };

     $scope.$on('$ionicView.beforeEnter', function() {
        imanUsbPort.start();
     });
     $scope.$on('$ionicView.afterLeave', function() {
        imanUsbPort.stop();
     });

     $scope.$on('imanUsbPort.input', function(e, inputStr) {
        imanDialog.toastBottom(inputStr);
        $scope.data.newBarcode = inputStr;
        
     });

}]);